package com.csx.governance.traffic.mq.rocketmq;

import cn.hutool.core.collection.CollectionUtil;
import com.csx.governance.traffic.core.TrafficGovernanceRuleLocator;
import com.csx.governance.traffic.mq.rocketmq.config.RocketMqRulesConfiguration;
import com.csx.governance.traffic.mq.rocketmq.model.RocketMqServiceRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author cuisongxu
 * @date 2023/3/5 15:07
 */
public class RocketMqGovernanceRuleLocator implements TrafficGovernanceRuleLocator<RocketMqServiceRule> {

    private static final Logger logger = LoggerFactory.getLogger(RocketMqGovernanceRuleLocator.class);

    private final RocketMqRulesConfiguration rules;

    private volatile Map<String, RocketMqServiceRule> serviceNameToRocketMqRuleMap = new HashMap<>();

    public RocketMqGovernanceRuleLocator(RocketMqRulesConfiguration rules) {
        this.rules = rules;
    }

    @Override
    public void refresh() {
        logger.info("rocketmq Governance Rule begin refresh");
        serviceNameToRocketMqRuleMap = rules.stream()
                .filter(RocketMqServiceRule::getEnabled)
                .collect(Collectors.toMap(RocketMqServiceRule::getServiceName, Function.identity()));
        logger.info("rocketmq Governance Rule finish refresh");
    }

    @Override
    public RocketMqServiceRule locateRule(String serviceName) {
        // 某些时机还没有触发统一刷新，但是需要使用到刷新后的Map，因此需要提前进行刷新
        if(CollectionUtil.isEmpty(serviceNameToRocketMqRuleMap)) {
            refresh();
        }
        return serviceNameToRocketMqRuleMap.get(serviceName);
    }
}
